//
//  BLSearchViewController.swift
//  BLLiveTelecast
//
//  Created by BigL055 on 16/6/20.
//  Copyright © 2016年 bigL.liveTelecast.com. All rights reserved.
//

import UIKit
/// 搜索历史数组
var searchHistoryArray = [String]()

class BLSearchViewController: UIViewController {
    
    /// 顶部占位视图
    var topPlaceView = UIView()
    /// 底部占位视图
    var bottomPlaceView = UIView()
    /// 动画图层
    var animationView = BLAnimationView()
    /// 搜索历史 tableView
    let searchHistoryTableView = UITableView(frame: CGRectZero, style: UITableViewStyle.Plain)
    let searchHistoryTableViewCellID = "searchHistoryTableViewCellID"
    
    /// 搜索完毕 Collection
    var didSearchCollectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: BLSubListFlowLayout())
    
    let didSearchCollectionViewCellID = "didSearchCollectionViewCellID"

    
    /// 搜索时标签
    let searchLeftButton = UIButton(type: .Custom)
    let clearSearchHistoryButton = UIButton(type: .Custom)
    
    /// 搜索后标签
    let didSearchLeftButton = UIButton(type: .Custom)
    let didSearchRightButton = UIButton(type: .Custom)
    
    
    /// 搜索到的room数组
    var roomArray = [BLDouyuRoomDetalModal]()
    

    
    /// 设置tableCell的高度
    let cellHeight :CGFloat = 40
    
    /// 搜索内容
    var searchText = ""

    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        setupUI()
        
        
        
    }
    
}

// MARK: - UI设置
extension BLSearchViewController{
    
    func setupUI() {
        // navbar
        setupNavigationItem()
        // 占位视图
        setupPlaceView()
        // 动画图层
        setupAnimationView()
        // 标签栏
        setupSearchSubButtonView()
        setupDidSearchSubButtonView()
        // 底部数据展示
        setupSearchHistoryTableView()
        setupdidSearchCollectionView()
        // UI显示事件
        BeginSearch()
        
    }
    
    /// 设置NavigationItem中内容
    func setupNavigationItem() {
        
        // 设置搜索框
        let searchBar = UISearchBar()
        searchBar.delegate = self
        searchBar.barStyle = .Black
        searchBar.placeholder = "搜索房间ID,主播名称"
        navigationItem.titleView = searchBar
    }
    
    /// 设置动画图层
    func setupAnimationView() {
        view.addSubview(animationView)
        animationView.snp_makeConstraints { (make) in
            make.top.equalToSuperview().offset(BL_NavigationBarHeight)
            make.left.right.bottom.equalToSuperview()
        }
    }
    
    /// 设置占位视图
    func setupPlaceView() {
        view.addSubview(topPlaceView)
        topPlaceView.snp_makeConstraints { (make) in
            make.top.equalToSuperview().offset(BL_StatusBarAndNavigationBarHeight)
            make.right.left.equalToSuperview()
            make.height.equalTo(cellHeight)
        }
        view.addSubview(bottomPlaceView)
        bottomPlaceView.snp_makeConstraints { (make) in
            make.right.left.bottom.equalToSuperview()
            make.top.equalTo(topPlaceView.snp_bottom)
        }
    }
    
    /// 设置编辑时标签栏
    func setupSearchSubButtonView() {
        
        searchLeftButton.setTitle("历史搜索", forState: UIControlState.Normal)
        searchLeftButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        searchLeftButton.titleLabel?.font = bl_Font_14
        searchLeftButton.sizeToFit()
        topPlaceView.addSubview(searchLeftButton)
        searchLeftButton.snp_makeConstraints { (make) in
            make.left.equalToSuperview().offset(BL_Magin)
            make.centerY.equalToSuperview()
        }
        
        clearSearchHistoryButton.setTitle(" 清空", forState: UIControlState.Normal)
        clearSearchHistoryButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        clearSearchHistoryButton.setImage(UIImage(named: "btn_search_clean_14x14_"), forState: UIControlState.Normal)
        clearSearchHistoryButton.titleLabel?.font = bl_Font_14
        clearSearchHistoryButton.addTarget(self, action: #selector(clearSearchHistoryButtonClick), forControlEvents: UIControlEvents.TouchUpInside)
        
        clearSearchHistoryButton.sizeToFit()
        topPlaceView.addSubview(clearSearchHistoryButton)
        clearSearchHistoryButton.snp_makeConstraints { (make) in
            make.right.equalToSuperview().offset(-BL_Magin)
            make.centerY.equalToSuperview()
        }
    }
    
    /// 设置编辑时搜索历史界面 tableView
    func setupSearchHistoryTableView() {
        searchHistoryTableView.delegate = self
        searchHistoryTableView.dataSource = self
        searchHistoryTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: searchHistoryTableViewCellID)
        bottomPlaceView.addSubview(searchHistoryTableView)
        searchHistoryTableView.snp_makeConstraints { (make) in
            make.top.right.left.bottom.equalToSuperview()
        }
        
    }
    
    
    /// 设置搜索后标签栏
    func setupDidSearchSubButtonView() {
        
        didSearchLeftButton.setTitle("搜索结果", forState: UIControlState.Normal)
        didSearchLeftButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        didSearchLeftButton.titleLabel?.font = bl_Font_14
        didSearchLeftButton.sizeToFit()
        topPlaceView.addSubview(didSearchLeftButton)
        didSearchLeftButton.snp_makeConstraints { (make) in
            make.left.equalToSuperview().offset(BL_Magin)
            make.centerY.equalToSuperview()
        }
        
        didSearchRightButton.setTitle("默认排序", forState: UIControlState.Normal)
        didSearchRightButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        didSearchRightButton.titleLabel?.font = bl_Font_14
        
        didSearchRightButton.sizeToFit()
        topPlaceView.addSubview(didSearchRightButton)
        didSearchRightButton.snp_makeConstraints { (make) in
            make.right.equalToSuperview().offset(-BL_Magin)
            make.centerY.equalToSuperview()
        }
    }
    
    
    /// 设置搜索后界面 collection
    func setupdidSearchCollectionView() {
        
        didSearchCollectionView.backgroundColor = UIColor.purpleColor()
        didSearchCollectionView.delegate = self
        didSearchCollectionView.dataSource = self
        didSearchCollectionView.registerNib(UINib.init(nibName: String(BLSubListCell), bundle: nil), forCellWithReuseIdentifier: didSearchCollectionViewCellID)
        bottomPlaceView.addSubview(didSearchCollectionView)
        didSearchCollectionView.snp_makeConstraints { (make) in
            make.top.right.left.bottom.equalToSuperview()
        }
    }
}

// MARK: - UI显示事件
extension BLSearchViewController{
    
    /// 开始搜索 - UI显示事件
    func BeginSearch() {
        didSearchLeftButton.hidden  = true
        didSearchRightButton.hidden = true
        didSearchCollectionView.hidden = true
        
        searchLeftButton.hidden = false
        clearSearchHistoryButton.hidden = false
        searchHistoryTableView.hidden  = false
    }
    
    
    /// 结束搜索 - UI显示事件
    func didSearch() {
        didSearchLeftButton.hidden  = false
        didSearchRightButton.hidden = false
        didSearchCollectionView.hidden = false

        clearSearchHistoryButton.hidden = true
        searchLeftButton.hidden     = true
        searchHistoryTableView.hidden  = true
    }
    
}

// MARK: - 按钮事件响应
extension BLSearchViewController{
    /// 清除搜索历史
    func clearSearchHistoryButtonClick() {
        searchHistoryArray = [String]()
        searchHistoryTableView.reloadData()
    }
    
}

// MARK: - UISearchBar - Delegate
extension BLSearchViewController : UISearchBarDelegate {
    
    /// 搜索按钮点击的回调
    func searchBarSearchButtonClicked(searchBar: UISearchBar) {
        
        UIApplication.sharedApplication().keyWindow?.endEditing(true)
        searchText = searchBar.text!
        searchHistoryArray.append(searchBar.text!)
        searchHistoryTableView.reloadData()
        animationView.beginLoadingAnimation(2.0, speed: 0.2)
        getSearchData(0)
        didSearch()
        
    }
    

    

    
    /// 开始编辑
    func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
        roomArray = [BLDouyuRoomDetalModal]()
        didSearchCollectionView.reloadData()
        BeginSearch()
    }
    
}

// MARK: - 搜索历史 tableView - UITableViewDelegate,UITableViewDataSource
extension BLSearchViewController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return searchHistoryArray.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(searchHistoryTableViewCellID, forIndexPath: indexPath)
        cell.textLabel?.text = searchHistoryArray[indexPath.item]
        return cell
    }
    
    
}

// MARK: - 结束搜索返回的房间 UICollectionViewDelegate,UICollectionViewDataSource
extension BLSearchViewController : UICollectionViewDelegate,UICollectionViewDataSource{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return roomArray.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(didSearchCollectionViewCellID, forIndexPath: indexPath) as! BLSubListCell
        cell.subListItem = roomArray[indexPath.item]
        if indexPath.item == (roomArray.count - 1) {
            getSearchData(roomArray.count)
        }
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let roomVC = BLRoomViewController()
        let item = roomArray[indexPath.item]
        roomVC.roomID = item.room_id!
        navigationController?.pushViewController(roomVC, animated: true)
    }
    
}

// MARK: - 网络请求
extension BLSearchViewController{
    
    func getSearchData(offset : Int) {
        BLGetDouyuData.shareInstance.getSearchNewData(searchText, limit: 10, offset: offset) { (dataModal) in
            self.roomArray = dataModal.roomlistArray
            self.didSearchCollectionView.reloadData()
        }
    }
}